import {
  setToken,
  removeToken,
  getToken,
  setRouter,
  getRouter,
  getMenus,
  setMenus,
  removeMenus,
  removeRouter,
  setLoginState,
  getLoginState,
  getUserInfo,
  setUserInfo,
  getRefreshToken,
  setRefreshToken, 
  getSiteInfo, 
  setSiteInfo,
  getSubApp, 
  setSubApp
} from "@/utils/storage";
import { createTreeData } from '@/utils/setting'
import {getUserRoutes, refreshToken, getUserInfo as getUserInfoApi} from '@/api/user'
import {getSubAppList} from '@/api/setting'
import { userLogout } from "@/api/user";
import router from '@/router'
const getDefaultState = () => {
  return {
      token: getToken(),
      refresh_token: getRefreshToken(),
      loginState: !Number(getLoginState()) && getToken(),
      name: '',
      user_info: getUserInfo(),
      roleRoutes: getRouter(),
      roleMenus: getMenus(),
      subApp:getSubApp() //子系统列表
  }
}
const state = getDefaultState()

const mutations = {
  // 重置vuex用户信息，退出登录使用
  RESET_STATE: state => {
      Object.assign(state, getDefaultState())
  },
  // 存储token及登录伴随fce,mfa
  SET_LOGIN_INFO: (state, data) => {
      state.token = data.token
      state.user_info = data.user_info
      state.refresh_token = data.refresh_token
      setToken(data.token)
      setUserInfo(data.user_info)
      setRefreshToken(data.refresh_token)
      if(data.mfa === 1 || data.fce === 1){
          setLoginState(1)
      }else{
          setLoginState(0)
      }
  },
  SET_USER_INFO: (state, data) => {
      state.user_info = JSON.parse(JSON.stringify(data))
      setUserInfo(data)
  },
  SET_TOKEN: (state, data) => {
      state.token = data.token
      setToken(data.token)
  },
  REMOVE_TOKEN: state => {
      state.token = ''
      removeToken() // 清除token
      removeMenus() // 清除Menus
      removeRouter() // 清除Router
      setLoginState(1)
  },
  SET_ROUTES: (state, routes) => {
      state.roleRoutes = routes
      setRouter(routes)
      router.dynamicRoutes()
  },
  SET_MENU: (state, menus) => {
      setMenus(menus)
      state.roleMenus = menus
  },
  SET_REFRESH_TOKEN: (state, data) => {
      state.refresh_token = data.refresh_token
      setRefreshToken(data.refresh_token)
  },
  SET_SUBAPP: (state, data) => {
      state.subApp = data.list
      setSubApp(data.list)
  }
}

const actions = {
  //更新菜单、子系统列表、路由 
  initLogin({ commit }){
      return new Promise((resolve, reject) => {
          getUserInfoApi().then(res => {
              commit('SET_USER_INFO', (res.data))
          })
          getSubAppList({pageSize: 100,currentPage: 1}).then(res => {
              commit('SET_SUBAPP', (res.data))
          })
          getUserRoutes().then(res => {
              // 拿到数据，构建树结构(路由菜单分别创建)
              commit('SET_ROUTES',createTreeData(res.data,'prouter'))
              const treeData = createTreeData(res.data)
              const menus = treeData
              commit('SET_MENU', menus)
              if (res.code === 20000) resolve(menus)
              else reject('error')
          })
      })
  },
  // 退出登录
  logout({ commit }){
    return new Promise((resolve, reject) => {
        userLogout().then(res => {
            commit('RESET_STATE')
            commit('REMOVE_TOKEN')
            if (res.code) resolve()
            else reject('error')
        })
    })
  },
  // 刷新token
  resetToken(context){
      return new Promise((resolve, reject) => {
          refreshToken().then(res => {
              context.commit('SET_TOKEN',res.data)
              context.commit('SET_REFRESH_TOKEN',res.data)
              if(res.data.uuid){
                  let siteInfo = getSiteInfo()
                  siteInfo.uuid = res.data.uuid
                  setSiteInfo(siteInfo)
                  context.rootState.app.site_info.uuid = res.data.uuid
              }
              resolve(res)
          }).catch(error => {
              reject(error)
          })
      })
  }
}

export default {
  namespaced: true, //命名空间
  state,
  mutations,
  actions,
}
